package com.firewolf.hibernate.relationship.many_one.main;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.firewolf.hibernate.relationship.many_one.dto.Customer;
import com.firewolf.hibernate.relationship.many_one.dto.Order;

public class MainDriver {

	private SessionFactory factory;

	private Session session;

	private Transaction transaction;

	@Test
	public void testSave() {
		openSession();

		Customer cus = new Customer();
		cus.setCustomerName("刘兴");

		Order o1 = new Order();
		o1.setCustomer(cus);
		o1.setOrderName("订单1");

		Order o2 = new Order();
		o2.setCustomer(cus);
		o2.setOrderName("111");

		//先保存customer，会生成3条insert语句
		session.save(cus);
		session.save(o1);
		session.save(o2);
		
		//先保存order，会生成3条insert语句，2条update语句
//		session.save(o1);
//		session.save(o2);
//		session.save(cus);

		closeSession();
	}
	
	/***
	查询的时候，
	①.如查询多的一端的对象，如果没有用到1的一端的对象，就只会生成查询n端对象的语句，当真的要用到1端的对象的时候，才会发送1端的查询语句
	②.若获取1端的对象的时候session已经关闭了，就会抛出LazyInitializationException异常
	 */
	@Test
	public void testQry(){
		openSession();
		Order o = (Order) session.get(Order.class, 1);
		//此时只会发送一条语句
		System.out.println(o.getOrderName());
		System.out.println("---------");
		//此时如果关闭session，再获取customer相关信息的时候，就会抛出异常
//		session.close();
		//真正用到customer，会发送sql语句
		System.out.println(o.getCustomer().getCustomerName());
		closeSession();
	}
	
	/**
	没有设置级联属性的时候，如果1 的一端被n的一端引用了，那么删除1的一端不会成功
	 */
	@Test
	public void testDel(){
		openSession();
		Customer c = (Customer) session.get(Customer.class,1);
		session.delete(c);
		closeSession();
	}

	private void openSession() {
		session = factory.openSession();
		transaction = session.beginTransaction();
	}
	
	private void closeSession() {
		transaction.commit();
		session.close();
	}

	@Before
	public void init() {
		Configuration cfg = new Configuration().configure("many2one.xml");

		ServiceRegistry registry = new ServiceRegistryBuilder().applySettings(cfg.getProperties())
				.buildServiceRegistry();
		factory = cfg.buildSessionFactory(registry);
	}

	@After
	public void destory() {
		factory.close();
	}
}
